package com.ydl.zhwc.mvpandrxjava.sample;

import com.ydl.zhwc.mvpandrxjava.bean.HeWeather6;
import com.ydl.zhwc.mvpandrxjava.bean.Now;
import com.ydl.zhwc.mvpandrxjava.bean.Total;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2017/12/22
 */

public class RxUtils {

    public static ObservableTransformer<HeWeather6, Now> handlerThrowable() {
        return new ObservableTransformer<HeWeather6, Now>() {
            @Override
            public ObservableSource<Now> apply(Observable<HeWeather6> upstream) {
                return upstream.flatMap(new Function<HeWeather6, ObservableSource<Now>>() {
                    @Override
                    public ObservableSource<Now> apply(HeWeather6 heWeather6) throws Exception {
                        List<Total> totals = heWeather6.weather;
                        if (totals.isEmpty()) {
                            return Observable.error(new ApiThrowable("..."));
                        }
                        Total total = totals.get(0);
                        String status = total.status;
                        if (!"ok".equals(status)) {
                            return Observable.error(new ApiThrowable(status));
                        }
                        return Observable.just(total.now);
                    }
                });
            }
        };
    }


    public static String getErrorMsg(Throwable throwable) {

        if (throwable instanceof ApiThrowable) {
            return throwable.getMessage();
        }

        return "其他错误";
    }

}
